<?php

/**
 * @file IndexController
 * @author garypradoruiz <garypradoruiz@gmail.com>
 * @link mailto:garypradoruiz@gmail.com
 * @copyleft 2012 garypradoruiz
 * @license GPL
 * @version 1
 */
class Orden_OrdenController extends Zend_Controller_Action {
    /*
     * status orden
     */

    protected $_PENDING = 0;
    protected $_PROGRESS = 1;
    protected $_PENDING_CLIENT = 2;
    protected $_CHANGES = 3;
    protected $_DENY = 4;
    protected $_APPROVED = 5;
    protected $_COMMITED = 6;
    protected $_SEND_EMAIL_NEW_ORDER = 0;
    protected $_SEND_EMAIL_CHANGE_ORDER = 1;
    protected $_SEND_EMAIL_DENY_ORDER = 2;

    public function init() {
        /* Initialize action controller here */
    }

    /*
     * Function that only show orders client logued
     */

    public function indexAction() {
        $ordenDb = new Orden_Model_DbTable_Orden();

        $select = $ordenDb->select()->setIntegrityCheck(false)
                        ->from(array('o' => 'orden'), array('code', 'title', 'create_date_orden' => 'create_date', 'end_date', 'status'))
                        ->join(array('ou' => 'orden_user'), 'o.id = ou.id_orden')
                        ->join(array('u' => 'user'), 'u.id = ou.id_user')
                        ->join(array('cl' => 'client'), 'cl.id = u.client_departament')->group('o.id');

        $dataOr = $ordenDb->fetchAll($select);
        $this->view->ordenes = $dataOr;
    }

    /*
     * Orden edited and status admin of agency 
     */

    public function editOrdenAction() {
        $ordenDb = new Orden_Model_DbTable_Orden();
        $id_orden = $this->_request->getParam('id', 0);

        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->getRequest()->isPost()) {
            $data = $this->_request->getParams();

            if ($data['radio_status'] == $this->_PROGRESS) {
                $descriptionDeny = $data['deny_description'];
                $where = $ordenDb->getAdapter()->quoteInto('id=?', $id_orden);
                $newData = array(
                    'status' => $this->_PROGRESS,
                    'deny_description' => $descriptionDeny
                );
                $ordenDb->update($newData, $where);
                $msg = 'Orden Aceptada. Un mensaje de confirmaci&oacute;n ha sido enviado a su correo y una copia a los encargados de agencia. 
                        Codigo de Orden: ' . 'XAVR' . $id_orden;
                $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                $sendEmail->sendEmail($id_orden, 'ORDEN_ACCEPT'); // Enviar email si la orden fue aceptada
            } else {  // Deny Orden and send email to client
                if ($data['radio_status'] == $this->_DENY) {
                    $descriptionDeny = $data['deny_description'];
                    $where = $ordenDb->getAdapter()->quoteInto('id=?', $id_orden);
                    $newData = array(
                        'status' => $this->_DENY,
                        'deny_description' => $descriptionDeny
                    );
                    $ordenDb->update($newData, $where);
                    $msg = 'Orden requiere mas informacion. Un mensaje de confirmaci&oacute;n ha sido enviado a su correo y una copia a los encargados de agencia. 
                            Codigo de Orden: ' . 'XAVR' . $id_orden;
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id_orden, 'ORDEN_DENY'); // Enviar email si la orden fue denegada
                }
            }
            $this->_helper->FlashMessenger()
                    ->setNamespace('success')
                    ->addMessage($msg);
            $this->_helper->redirector->gotoUrlAndExit('/orden/orden/index');
        } else {
            $id = $this->_request->getParam('id', 0);
            $ordenDb = new Orden_Model_DbTable_Orden();
            $select = $ordenDb->select()->where('id=?', $id)->where('deleted=?', '0');
            $result = $ordenDb->fetchRow($select);
            $this->view->orden = $result;

            $ordenDep = new Orden_Model_DbTable_OrdenDepartament();
            $selectDep = $ordenDb->select()->setIntegrityCheck(false)
                    ->from(array('od' => 'orden_departament'), array('id_departament'))->where('id_orden=?', $id)
                    ->join(array('d' => 'departament'), 'od.id_departament = d.id');
            $dataOrdenDep = $ordenDep->fetchAll($selectDep);
            $this->view->dataOrdenDep = $dataOrdenDep;

            $ordenDepJob = new Orden_Model_DbTable_OrdenJob();
            $selectDepJob = $ordenDb->select()->setIntegrityCheck(false)
                            ->from(array('odj' => 'orden_job'), array('*'))->where('id_orden=?', $id);
            $dataOrdenDepJob = $ordenDepJob->fetchAll($selectDepJob);
            $this->view->dataOrdenDepJob = $dataOrdenDepJob;

            $attachment = new Attachment_Model_DbTable_Attachment();
            $dataOrdenAttach = $attachment->fetchAll('id_order=' . $id);
            $this->view->dataOrdenAttach = $dataOrdenAttach;
        }
    }

    /*
     * Detail of orden only ordenes of a user client
     * also change status and add comment to orden
     */

    public function viewDetailOrdenAction() {
        $id = $this->_request->getParam('id', 0);
        $ordenDb = new Orden_Model_DbTable_Orden();
        $messageDb = new Orden_Model_DbTable_OrdenMessage();
        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->_request->isPost()) {
            $data = $this->_request->getParams();

            $ordenDb->update(array('status' => $data['status']), 'id=' . $data['id_orden']);
            $reviewJob = implode(",", $data['checkJob']);
            $messageDb->insert(array('message' => $data['message'], 'id_orden' => $data['id_orden'], 'id_user' => $iduser, 'review_job' => $reviewJob));

            // enviar email con el cambio de estado
            $where = $ordenDb->getAdapter()->quoteInto('id=?', $id);
            $newData = array(
                'status' => $data['status']
            );
            $ordenDb->update($newData, $where);

            switch ($data['status']) {
                case 2:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_ATHOS_REVIEW'); // pendiente con cliente
                    break;
                case 3:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_ATHOS_REVISED'); /// cambios
                    break;
                case 5:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_ATHOS_COMPLETE'); /// aprobado
                    break;
                case 6:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_ATHOS_COMMITED'); /// entregado
                    break;
            }
            $this->_helper->FlashMessenger()
                    ->setNamespace('success')
                    ->addMessage('Usted realizo el cambio de estado en la orden XAVR' . $data['id_orden'] . ', se notificara a los involucrados para proceder.');
            $this->_redirect('/orden/orden/index');
        } else {
            $result = $ordenDb->fetchRow('id=' . $id);
            $this->view->details = $result;

            //agencias involucradas en la orden...
            $ordenDep = new Orden_Model_DbTable_OrdenDepartament();
            $selectDep = $ordenDb->select()->setIntegrityCheck(false)
                    ->from(array('od' => 'orden_departament'), array('id_departament'))->where('id_orden=?', $id)
                    ->join(array('d' => 'departament'), 'od.id_departament = d.id');
            $dataOrdenDep = $ordenDep->fetchAll($selectDep);
            $this->view->dataOrdenDep = $dataOrdenDep;

            //trabajos a realizar dentro de la orden...
            $ordenDepJob = new Orden_Model_DbTable_OrdenJob();
            $selectDepJob = $ordenDb->select()->setIntegrityCheck(false)
                            ->from(array('odj' => 'orden_job'), array('*'))->where('odj.id_orden=?', $id)->order('id asc');
            $dataOrdenDepJob = $ordenDepJob->fetchAll($selectDepJob);
            $this->view->dataOrdenDepJob = $dataOrdenDepJob;

            //adjuntos de la orden..
            $attachment = new Attachment_Model_DbTable_Attachment();
            $dataOrdenAttach = $attachment->fetchAll('id_order=' . $id);
            $this->view->dataOrdenAttach = $dataOrdenAttach;
        }
    }

    public function saveDateJobAction() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $ordenJob = new Orden_Model_DbTable_OrdenJob();
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $idorden = $request->getParam('idorden', 0);
            $idjob = $request->getParam('idjob', 0);
            $dateClient = $request->getParam('dateClient');
            $dateAgency = $request->getParam('dateAgency');

            $ordenJob->update(
                    array('end_date_client' => date('Y-m-d', strtotime($dateClient)),
                'begin_date_agency' => date('Y-m-d', strtotime($dateAgency))), 'id=' . $idjob . ' and id_orden=' . $idorden
            );
        }
    }

    public function ordenCompletAction() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $orden = new Orden_Model_DbTable_Orden();
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $id = $request->getParam('id', 0);
            $orden->update(array('status' => $this->_APPROVED), 'id=' . $id);
            echo 'orden aprobada por completo';
        }
    }

    public function commentJobAction() {
        $this->_helper->layout()->disableLayout();
        $request = $this->getRequest();

        if ($request->isXmlHttpRequest()) {
            $id_orden = $request->getParam('id_orden', 0);
            $id_job = $request->getParam('id_job', 0);

            $this->view->name_job = $request->getParam('name', '');
            $this->view->id_orden = $id_orden;
            $this->view->id_job = $id_job;

            $ordenJobActivity = new Orden_Model_DbTable_OrdenJobActivity();
            $selectMessage = $ordenJobActivity->select()->setIntegrityCheck(false)
                    ->from(array('oda' => 'orden_job_activity'), array('id_job_activity' => 'oda.id', 'id_orden', 'message', 'register_date', 'id_job', 'status'))
                    ->where('oda.id_orden=?', $id_orden)->where('id_job=?', $id_job)
                    ->join(array('u' => 'user'), 'u.id = oda.id_user');
            $this->view->resultJobActivity = $ordenJobActivity->fetchAll($selectMessage);
        }
    }

    public function saveCommentAction() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $ordenJobAct = new Orden_Model_DbTable_OrdenJobActivity();
        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $request->getParams();

            $dataR = array(
                'id_orden' => $data['id_orden'],
                'id_job' => $data['id_job'],
                'id_user' => $iduser,
                'status' => $data['status'],
                'message' => $data['detail']
            );

            $x = $ordenJobAct->insert($dataR);
            if ($x != 0) {
                //update status orden departament job
                $ordenJob = new Orden_Model_DbTable_OrdenJob();
                $dataUpdate = array('status' => $data['status']);
                if ($data['status'] == $this->_APPROVED) {
                    $dataUpdate['end_date_agency'] = date('Y-m-d');
                }
                $ordenJob->update(($dataUpdate), 'id_orden=' . $data['id_orden'] . ' and id=' . $data['id_job']);
                // send email 
                $this->sendMessageComment($data['id_orden'], $data['status']);

                $selectMessage = $ordenJobAct->select()->setIntegrityCheck(false)
                                ->from(array('oda' => 'orden_job_activity'), array('id_orden', 'message', 'register_date', 'id_job', 'status'))
                                ->where('oda.id=?', $x)->join(array('u' => 'user'), 'u.id = oda.id_user');
                $jsonData = Zend_Json::encode($ordenJobAct->fetchRow($selectMessage)->toArray());
                echo $jsonData;
            }
        }
    }

    public function observationClassifiedAction() {
        $this->_helper->layout()->disableLayout();
        $request = $this->getRequest();
        $ordenActivityDb = new Orden_Model_DbTable_OrdenJobActivity();
        $ordenTypeClassifiedDb = new Orden_Model_DbTable_OrdenJobTypeClassified();

        if ($request->isXmlHttpRequest()) {
            $id_orden = $request->getParam('id_orden', 0);
            $id_job = $request->getParam('id_job', 0);
            $id_activity = $request->getParam('id', 0);

            $selectActivity = $ordenActivityDb->select()->where('id=?', $id_activity)->where('id_orden=?', $id_orden)->where('id_job=?', $id_job);
            $this->view->jobActivity = $ordenActivityDb->fetchRow($selectActivity);

            $selectActObs = $ordenTypeClassifiedDb->select()
                    ->where('id_orden_job_activiy=?', $id_activity)
                    ->where('id_orden=?', $id_orden);

            if ($ordenTypeClassifiedDb->fetchAll($selectActObs) != null) {
                $this->view->observation = $ordenTypeClassifiedDb->fetchAll($selectActObs);
            } else {
                $this->view->observation = null;
            }
            $this->view->name_job = $request->getParam('name', '');

            /* Obtenemos el cliente de la orden. ex: tigo, sofia */
            $ordenUserDb = new Orden_Model_DbTable_OrdenUser();

            $selectClient = $ordenUserDb->select()->setIntegrityCheck(false)
                    ->from(array('ou' => 'orden_user'), array('*'))->where('id_orden=?', $id_orden)
                    ->join(array('cl' => 'client'), 'cl.id = ou.id_client');

            $dataClient = $ordenUserDb->fetchRow($selectClient);
            $this->view->client = $dataClient;
        }
    }

    public function saveObservationAction() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $request = $this->getRequest();
        $ordenTypeClassifiedDb = new Orden_Model_DbTable_OrdenJobTypeClassified();

        if ($request->isXmlHttpRequest()) {
            $data = $request->getParams();
            if (isset($data['checkClient'])) {
                $checkClient = $data['checkClient'];
            }
            if (isset($data['checkResponsabilidadVelcro'])) {
                $responsability_velcro = $data['checkResponsabilidadVelcro'];
            }
            if (isset($data['checkResponsabilidadAthos'])) {
                $responsability_athos = $data['checkResponsabilidadAthos'];
            }
            if (isset($data['checkResponsabilidadRaza'])) {
                $responsability_raza = $data['checkResponsabilidadRaza'];
            }
            //delete all data
            $ordenTypeClassifiedDb
                    ->delete('id_orden_job_activiy=' . $data['id_orden_job_activiy'] . ' and id_orden=' . $data['id_orden'] . ' and id_job=' . $data['id_job']);
            // registry newly
            foreach ($data['checkObs'] as $check) {
                $ordenTypeClassifiedDb->insert(array(
                    'id_orden' => $data['id_orden'],
                    'id_orden_job_activiy' => $data['id_orden_job_activiy'],
                    'id_job' => $data['id_job'],
                    'detail' => $data['detail'],
                    'type' => $check,
                    'responsibility_velcro' => $responsability_velcro,
                    'responsibility_athos' => $responsability_athos,
                    'responsibility_velcro' => $responsability_raza,
                    'responsibility_client' => $checkClient
                ));
            }
        }
    }

    private function sendMessageComment($idOrden=0, $status=0) {
        if ($idOrden != 0 && $status != 0) {
            switch ($status) {
                case 2:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($idOrden, 'ORDEN_ATHOS_REVIEW'); // pendiente con cliente
                    break;
                case 3:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($idOrden, 'ORDEN_ATHOS_REVISED'); /// cambios
                    break;
                case 5:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($idOrden, 'ORDEN_ATHOS_COMPLETE'); /// aprobado
                    break;
                case 6:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($idOrden, 'ORDEN_ATHOS_COMMITED'); /// entregado
                    break;
            }
        }
    }

}

?>